<?php
namespace frontend\modules\pay\controllers\wechat;
use backend\modules\business\models\BusinessPig;
use common\models\business\BusinessGrowup;
use common\models\business\BusinessUser;
use common\models\business\BusinessUserScorerecord;
use common\models\shop\ShopGoods;
use common\models\shop\ShopHouseOrder;
use common\models\shop\ShopOrder;
use common\models\shop\ShopOrderGoods;
use common\models\shop\ShopRaisingOrder;
use common\models\sys\SysSetting;
use frontend\controllers\BaseMobileController;
use yii\db\Query;
use yii\helpers\ArrayHelper;

/**
 * Site controller
 */
class CallbackController extends BaseMobileController
{
    public $enableCsrfValidation = false;

    public function actionIndex()
    {
        echo 123123;
    }


    /**
     * @return mixed
     * 购买商品支付异步通知地址
     */
    public function actionNotifyShopPay()
    {
        $response = \Yii::$app->wechat->payment->handleNotify(function($notify, $successful){
            \Yii::info($notify);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = ShopOrder::find()
                ->where('ordersn=:sn',[':sn'=>$notify->out_trade_no])
                ->asArray()
                ->one();


            if($notify->total_fee != ($order['price']*100)){
                \Yii::info('订单金额与实际不符');
                return 'Order has a problem!';
            }


            if (!$order) { // 如果订单不存在
                \Yii::info('订单没有找到');
                return 'Order not exist.'; //订单没找到，别再通知我了
            }

            // 检查订单是否已经更新过支付状态
            if ($order['status'] == 1) {
                \Yii::info('订单状态已经为支付状态');
                return true;
            }
            // 用户是否支付成功
            if ($successful) {
                \Yii::info('支付成功');
                // 不是已经支付状态则修改为已经支付状态
                $data['paytime'] = time(); // 更新支付时间为当前时间
                if($order['sendtype'] == 1){        //快递
                    $data['status'] = ShopOrder::STATUS_PAY;
                }else{          //自提，直接为已发货
                    $data['status'] = ShopOrder::STATUS_SEND;
                }
                $data['transid'] = $notify->transaction_id;
                $data['paydetail'] = serialize($notify);
                $data['paytype'] = ShopOrder::WECHAT_PAY;

                //取出购买的商品
                $allgoods = (new Query())->select('og.goodsid,g.total,g.sales,og.total as buynum,g.title')
                    ->from(ShopOrderGoods::tableName().' as og')
                    ->leftJoin(ShopGoods::tableName().' as g','og.goodsid=g.id')
                    ->where('og.orderid=:orderid',[':orderid' => $order['id']])
                    ->all();
                //减库存
                foreach ($allgoods as $key => $row){
                    \Yii::$app->db->createCommand('update '.ShopGoods::tableName().' set total=total-'.$row['buynum'].',sales=sales+'.$row['buynum'].' where id='.$row['goodsid'])
                    ->execute();
                }

            } else { // 用户支付失败
                \Yii::info('支付失败');
                $order['status'] = ShopOrder::STATUS_PAYFAIL;
            }

            \Yii::info('更新状态');
            $res = \Yii::$app->db->createCommand()->update(ShopOrder::tableName(),$data,'ordersn=:sn',[':sn'=>$notify->out_trade_no])->execute();


            //减少用户积分
            $radio = SysSetting::getValue('scoretomoney');
            $subscore = intval($order['creditmoney']/$radio);
            BusinessUser::setScore($order['userid'],-$subscore);
            BusinessUserScorerecord::opScore($order['userid'],-$subscore,'购买商品使用');

            //增加用户积分
            $moneytoscore = SysSetting::getValue('moneytoscore');
            $score = $order['price']*$moneytoscore;
            BusinessUser::setScore($order['userid'],$score);
            BusinessUserScorerecord::opScore($order['userid'],$score,'购买商品获得');

            //发送模板消息
            $titles = ArrayHelper::getColumn($allgoods,'title');
            $titles  = implode(',',$titles);
            $data = [
                "first"  => "恭喜您下单购买的“".$titles."”支付成功，",
                "keyword1"   => "支付成功",
                "keyword2"  => date('Y-m-d H:i:s'),
                "remark" => "牧心欢迎再次光临！",
            ];
            $notice = \Yii::$app->wechat->notice->to($order['from_user'])
                ->url(\Yii::$app->request->hostInfo.'/business/user/pork-order/index?status=1')
                ->template(SysSetting::getValue('template_msgid'))
                ->andData($data)
                ->send();

            return true; // 返回处理完成
        });
        $response->send();
    }


    /**
     * 领养仔猪支付完成异步通知
     */
    public function actionNotifyRasingPay()
    {
        $response = \Yii::$app->wechat->payment->handleNotify(function($notify, $successful){
            \Yii::info($notify);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = ShopRaisingOrder::find()
                ->where('ordersn=:sn',[':sn'=>$notify->out_trade_no])
                ->asArray()
                ->one();

            if (!$order) { // 如果订单不存在
                \Yii::info('订单没有找到');
                return 'Order not exist.'; //订单没找到，别再通知我了
            }

            \Yii::info('订单金额'.$notify->total_fee);
            //验证订单金额
            if($notify->total_fee != ($order['price']*100)){
                \Yii::info('订单金额与实际不符');
                return 'Order has a problem!';
            }


            // 检查订单是否已经更新过支付状态
            if ($order['status'] == ShopRaisingOrder::STATUS_PAY) {
                \Yii::info('订单状态已经为支付状态');
                return true;
            }

            // 用户是否支付成功
            if ($successful) {
                \Yii::info('支付成功');
                // 不是已经支付状态则修改为已经支付状态
                $data['paytime'] = time(); // 更新支付时间为当前时间
                $data['transid'] = $notify->transaction_id;
                $data['paydetail'] = serialize($notify);
                $data['status'] = ShopRaisingOrder::STATUS_PAY;
                $data['paytype'] = ShopRaisingOrder::WECHAT_PAY;

                //更新仔猪的领养人信息
                \Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['lingperson'=>$order['userid']],'id=:pigid',[':pigid'=>$order['pigid']])->execute();
                //更新订单状态
                $res = \Yii::$app->db->createCommand()->update(ShopRaisingOrder::tableName(),$data,'ordersn=:sn',[':sn'=>$notify->out_trade_no])->execute();
            } else { // 用户支付失败
                \Yii::info('支付失败');
                $order['status'] = ShopRaisingOrder::STATUS_PAYFAIL;
            }
            \Yii::info('支付完成');
            //更新用户积分
            $moneytoscore = SysSetting::getValue('moneytoscore');
            $score = $order['price']*$moneytoscore;
            BusinessUser::setScore($order['userid'],$score);
            //积分记录
            BusinessUserScorerecord::opScore($order['userid'],$score,'认养仔猪');

            //发送模板消息
            $data = [
                "first"  => "恭喜您下单领养的编号为“".$order['pigno']."”的仔猪支付成功，",
                "keyword1"   => "支付成功",
                "keyword2"  => date('Y-m-d H:i:s'),
                "remark" => "牧心欢迎再次光临！",
            ];
            $openid = (new Query())->select('openid')->from(BusinessUser::tableName())->where('id=:id',[':id'=>$order['userid']])->scalar();
            $notice = \Yii::$app->wechat->notice->to($openid)
                ->url(\Yii::$app->request->hostInfo.'/business/user/my-pigs')
                ->template(SysSetting::getValue('template_msgid'))
                ->andData($data)
                ->send();

            return true; // 返回处理完成
        });
        $response->send();
    }




    /**
     * 农家乐支付异步通知
     */
    public function actionNotifyHousePay()
    {
        $response = \Yii::$app->wechat->payment->handleNotify(function($notify, $successful){
            \Yii::info($notify);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = ShopHouseOrder::find()
                ->where('ordersn=:sn',[':sn'=>$notify->out_trade_no])
                ->asArray()
                ->one();

            if (!$order) { // 如果订单不存在
                \Yii::info('订单没有找到');
                return 'Order not exist.'; //订单没找到，别再通知我了
            }

            //验证订单金额
            if($notify->total_fee != ($order['price']*100)){
                \Yii::info('订单金额与实际不符');
                return 'Order has a problem!';
            }


            // 检查订单是否已经更新过支付状态
            if ($order['status'] == ShopHouseOrder::STATUS_PAY) {
                \Yii::info('订单状态已经为支付状态');
                return true;
            }

            // 用户是否支付成功
            if ($successful) {
                \Yii::info('支付成功');
                // 不是已经支付状态则修改为已经支付状态
                $data['paytime'] = time(); // 更新支付时间为当前时间
                $data['transid'] = $notify->transaction_id;
                $data['paydetail'] = serialize($notify);
                $data['status'] = ShopHouseOrder::STATUS_PAY;
                $data['paytype'] = ShopHouseOrder::WECHAT_PAY;


                //更新订单状态
                $res = \Yii::$app->db->createCommand()->update(ShopHouseOrder::tableName(),$data,'ordersn=:sn',[':sn'=>$notify->out_trade_no])->execute();
            } else { // 用户支付失败
                \Yii::info('支付失败');
                $order['status'] = ShopHouseOrder::STATUS_PAYFAIL;
            }
            \Yii::info('支付完成');

            //减少用户积分
            $radio = SysSetting::getValue('scoretomoney');
            $subscore = intval($order['scoreprice']/$radio);
            BusinessUser::setScore($order['userid'],-$subscore);
            BusinessUserScorerecord::opScore($order['userid'],-$subscore,'预定农家乐使用');

            //增加用户积分
            $moneytoscore = SysSetting::getValue('moneytoscore');
            $score = $order['price']*$moneytoscore;
            BusinessUser::setScore($order['userid'],$score);
            BusinessUserScorerecord::opScore($order['userid'],$score,'预定农家乐获得');


            return true; // 返回处理完成
        });
        $response->send();
    }






    /**
     * 宰杀支付
     */
    public function actionNotifyKillPay()
    {
        $response = \Yii::$app->wechat->payment->handleNotify(function($notify, $successful){
            \Yii::info($notify);
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = BusinessGrowup::find()
                ->where('ordersn=:sn',[':sn'=>$notify->out_trade_no])
                ->asArray()
                ->one();

            if (!$order) { // 如果订单不存在
                \Yii::info('订单没有找到');
                return 'Order not exist.'; //订单没找到，别再通知我了
            }

            //验证订单金额
            if($notify->total_fee != ($order['killprice']*100)){
                \Yii::info('订单金额与实际不符');
                return 'Order has a problem!';
            }


            // 检查订单是否已经更新过支付状态
            if ($order['status'] == BusinessGrowup::STATUS_PAY) {
                \Yii::info('订单状态已经为支付状态');
                return true;
            }

            // 用户是否支付成功
            if ($successful) {
                \Yii::info('支付成功');
                // 不是已经支付状态则修改为已经支付状态
                $data['paytime'] = time(); // 更新支付时间为当前时间
                $data['transid'] = $notify->transaction_id;
                $data['paydetail'] = serialize($notify);
                $data['status'] = BusinessGrowup::STATUS_PAY;
                $data['paytype'] = BusinessGrowup::WECHAT_PAY;


                //更新订单状态
                $res = \Yii::$app->db->createCommand()->update(BusinessGrowup::tableName(),$data,'ordersn=:sn',[':sn'=>$notify->out_trade_no])->execute();
            } else { // 用户支付失败
                \Yii::info('支付失败');
                $order['status'] = BusinessGrowup::STATUS_PAYFAIL;
            }
            \Yii::info('支付完成');

            //增加用户积分
            $moneytoscore = SysSetting::getValue('moneytoscore');
            $score = $order['killprice']*$moneytoscore;
            BusinessUser::setScore($order['userid'],$score);
            BusinessUserScorerecord::opScore($order['userid'],$score,'支付宰杀费用获得');


            //更新仔猪的状态
            \Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['status'=>BusinessPig::STATUS_WAITKILL],'id=:id',[':id'=>$order['pigid']])
                ->execute();

            //发送模板消息
            $data = [
                "first"  => "恭喜您下单领养的编号为“".$order['pigno']."”的仔猪宰杀费用支付成功，",
                "keyword1"   => "支付成功",
                "keyword2"  => date('Y-m-d H:i:s'),
                "remark" => "牧心欢迎再次光临！",
            ];
            $openid = (new Query())->select('openid')->from(BusinessUser::tableName())->where('id=:id',[':id'=>$order['userid']])->scalar();
            $notice = \Yii::$app->wechat->notice->to($openid)
                ->url(\Yii::$app->request->hostInfo.'/business/user/my-pigs?status=4')
                ->template(SysSetting::getValue('template_msgid'))
                ->andData($data)
                ->send();

            return true; // 返回处理完成
        });
        $response->send();
    }



}

